using System;
using System.Collections;

namespace Microsoft.Samples.Windows.Forms.Navigation
{
	/// <summary>
	/// A table that manages counts of references to objects.
	/// </summary>
	internal class ReferenceCountTable
	{
		private Hashtable countTable = new Hashtable();

		/// <summary>
		/// Return the current reference count for the given object.
		/// </summary>
		public int this [object o]
		{
			get
			{
				return countTable.ContainsKey(o) ? (int) countTable[o] : 0;
			}
		}

		/// <summary>
		/// Add a new reference to the given object.
		/// </summary>
		/// <param name="o">The object to add a reference to</param>
		public void AddReference(object o)
		{
			countTable[o] = this[o] + 1;
		}

		/// <summary>
		/// Remove a reference from the given object.
		/// </summary>
		/// <remarks>
		/// If the object has no references, calling the routine has no effect. No exception is thrown.
		/// </remarks>
		/// <param name="o">The object to remove a reference from</param>
		/// <returns>The object's new reference count</returns>
		public int RemoveReference(object o)
		{
			int newReferenceCount = this[o] - 1;

			if (newReferenceCount > 0)
			{
				// Store the decremented reference count.
				countTable[o] = newReferenceCount;
			}
			else
			{
				// The last reference has been removed. Remove the object from the table.
				countTable.Remove(o);
			}

			return newReferenceCount;
		}
	}
}
